﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Workflow.DwzCode;

namespace H2.NET.Web.Pages.SMD.InStock
{
    public partial class BudgetMaintain : BasePage
    {
        /// <summary>
        /// 预算余额
        /// </summary>
        public string BalanceBudget = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            var configService = new ConfigService();
            if (AksRequest.GetString("action") == "save")
            {
                var budgetMaintainDt =
                    configService.GetList(
                        "ParentId = (select configid from t_smd_Config where code='S_XYYS') order by seq").Tables[0];
                var updateSql = new StringBuilder();
                var inStockLogs = new List<t_smd_InStockLog>();

                foreach (DataRow row in budgetMaintainDt.Rows)
                {
                    decimal d_budget;
                    var budget = AksRequest.GetString("budget['" + row["code"] + "']");

                    if (string.IsNullOrEmpty(budget)) continue;

                    if (!decimal.TryParse(budget, out d_budget))
                    {
                        ErrorMsg("对不起，请输入正确的金额");
                        return;
                    }

                    if (d_budget == 0) continue;

                    updateSql.AppendLine("update t_smd_Config set value = cast(value as decimal) + " + budget +
                                         " where code = '" + row["code"] +
                                         "' and ParentId = (select configid from t_smd_Config where code='S_XYYS')");

                    // 变更日志
                    var inStockLog = new t_smd_InStockLog();
                    inStockLog.Category = "设备预算";
                    inStockLog.Amount = d_budget;
                    inStockLog.Content = row["name"] + "增加了" + d_budget.ToString("N");
                    inStockLog.CreateOn = DateTime.Now;
                    inStockLog.CreaterName = UserAPI.UserFullName;

                    inStockLogs.Add(inStockLog);
                }
                configService.BatchUpdate(updateSql.ToString());

                Storage.Save(Storage.Context3, inStockLogs.ToArray());

                SuccessMsg("BI/InStock/Index.aspx");
            }
            else
            {
                var budgetMaintainDt = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_XYYS') order by seq").Tables[0];

                rpt_balancebudget.DataSource = budgetMaintainDt;
                rpt_balancebudget.DataBind();
            }
        }
    }
}